import DEV from '@/config/dev.js'
import 'fs'
import {createReadStream} from 'fs'
import {web} from '@/config/dir.coffee'
import {join} from "path"
import {preload} from '@/config/dir.coffee'
import {net,session} from 'electron'

if DEV
  HTTP = """http://127.0.0.1:54910/"""
else
  HOST = "127.0.0.1"
  HTTP = "http://"+HOST

  session.defaultSession.protocol.interceptStreamProtocol("http", (req, next) =>
    url = new URL(req.url)
    if url.host == HOST
      {pathname} = url
      if pathname == '/'
        pathname += 'index.html'

      suffix = pathname[pathname.lastIndexOf('.')+1..]
      if suffix.startsWith 'htm'
        mime = "text/html"
      else
        mime = {
          js:'text/javascript'
          css:'text/css'
          svg:'image/svg+xml'
          woff2:'font/woff2'
        }[suffix] or 'application/octet-stream'

      data = createReadStream web+pathname
      next {
        data
        statusCode: 200
        headers:
          'content-type': mime
      }
    else
      req.useSessionCookies = true
      req.partition = 'persist:I'
      r = net.request req
      r.on 'response', (response)=>
        {headers,statusCode} = response
        next(
          data:response
          headers
          statusCode
        )
        return
      if req.uploadData
        for i from req.uploadData
          {bytes} = i
          if bytes
            r.write bytes
      r.end()
    return
  )


export default new Proxy(
  {}
  get:(self,hash)=>
    (config)=>
      # 去掉MAC圆角边框 feat: add roundedCorners option for BrowserWindow #27572 https://github.com/electron/electron/pull/27572
      config = {
        # closable:false # 是否可以被退出
        skipTaskbar:true # windows 隐藏任务栏
        frame: false # 无边框
        minimizable: false
        maximizable: false
        fullscreenable: false
        type:'toolbar'
        shadow:false
        hasShadow:false
        transparent:true
        #acceptFirstMouse: true
        webPreferences:{
          preload:join(preload, "p.js")
          #nodeIntegrationInWorker:true
          webSecurity: false
        }
        ...config
      }
      win = new BrowserWindow config
      win.setMenu(null)
      if hash!='main'
        win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })
      win.loadURL HTTP+"#"+hash

      win.once 'ready-to-show', =>
        win.show()

      win.focus()
      win
)
